package com.xiangty.reader;

import com.xiangty.bean.CustTemp;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.item.database.JdbcCursorItemReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.RowMapper;

import javax.sql.DataSource;
import java.sql.ResultSet;
import java.sql.SQLException;

@Configuration
public class JdbcCursorItemReaderConfiguration {

    @Autowired
    private DataSource dataSource;

    @Bean("jdbcCursorItemReader")
    @StepScope
    public JdbcCursorItemReader<CustTemp> jdbcCursorItemReader(
            @Value("#{stepExecutionContext[fromId]}") final String fromId,
            @Value("#{stepExecutionContext[toId]}") final String toId
    ) {

        System.out.println("------------JdbcPagingItemReader开始-------------【" + Thread.currentThread().getName() + "】--fromId: " + fromId + "  -----toId:" + toId);

        JdbcCursorItemReader<CustTemp> itemReader = new JdbcCursorItemReader<CustTemp>();
        itemReader.setDataSource(dataSource);
        itemReader.setSql("SELECT * FROM t_cust_temp WHERE id BETWEEN " + Integer.valueOf(fromId) + " AND " + Integer.valueOf(toId));
        itemReader.setRowMapper(new RowMapper<CustTemp>() {
            @Override
            public CustTemp mapRow(ResultSet rs, int rowNum) throws SQLException {
                CustTemp custTemp = new CustTemp();
                custTemp.setId(rs.getInt(1));
                custTemp.setCustNo(rs.getString(2));
                custTemp.setApplicationNo(rs.getString(3));
                custTemp.setValue1(rs.getString(4));
                custTemp.setValue2(rs.getString(5));
                custTemp.setValue3(rs.getString(6));
                custTemp.setValue4(rs.getString(7));
                custTemp.setValue5(rs.getString(8));
                custTemp.setValue6(rs.getString(9));
                custTemp.setValue7(rs.getString(10));
                custTemp.setValue8(rs.getString(11));
                custTemp.setValue9(rs.getString(12));
                custTemp.setValue10(rs.getString(13));
                custTemp.setValue11(rs.getString(14));
                custTemp.setValue12(rs.getString(15));
                custTemp.setValue13(rs.getString(16));
                custTemp.setValue14(rs.getString(17));
                custTemp.setValue15(rs.getString(18));
                custTemp.setValue16(rs.getString(19));
                custTemp.setValue17(rs.getString(20));
                custTemp.setValue18(rs.getString(21));
                custTemp.setValue19(rs.getString(22));
                custTemp.setValue20(rs.getString(23));
                return custTemp;
            }
        });

        return itemReader;
    }

}
